import userCenterLoginRecordApi from '@/api/userCenter/userCenterLoginRecordApi'
import CTable from '@/components/CTable/CTable'
import IRequestVO from '@/model/vo/request/IRequestVO'
import { handlerRegion } from '@/util/CommonUtil'
import { Modal } from '@douyinfe/semi-ui'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'

interface ILoginRecord {
  modalVisible: boolean
  setModalVisible: Dispatch<SetStateAction<boolean>>
}

const columns = [
  {
    title: '登录时间',
    dataIndex: 'createTime',
  },
  { title: 'ip', dataIndex: 'ip' },
  {
    title: 'ip区域',
    dataIndex: 'region',
    render: (text: any, record: IRequestVO, index: number) => {
      return handlerRegion(record.region!)
    },
  },
]

export default function LoginRecord(props: ILoginRecord) {
  const [dataSource, setDataSource] = useState<IRequestVO[]>([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageNum, setPageNum] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  useEffect(() => {
    setDataSource([]) // 重置 dataSource
    if (props.modalVisible === false) {
      return
    }
    setPageNum(1)
    setPageSize(10)
    getTableData(1, 10, setDataSource, setTotal, setLoading)
  }, [props.modalVisible])

  return (
    <Modal
      closeOnEsc
      footer={false}
      width={860}
      title="登录记录"
      visible={props.modalVisible}
      onCancel={() => {
        props.setModalVisible(false)
      }}
    >
      <CTable<IRequestVO>
        pagination={{
          total,
          currentPage: pageNum,
          pageSize,
          onChange: (currentPage: number, pageSize: number) => {
            setPageNum(currentPage) // 这里的值不会立即生效
            setPageSize(pageSize) // 这里的值不会立即生效
            getTableData(
              currentPage,
              pageSize,
              setDataSource,
              setTotal,
              setLoading
            )
          },
          showSizeChanger: true,
        }}
        scrollY={600}
        loading={loading}
        dataSource={dataSource}
        columns={columns}
      ></CTable>
    </Modal>
  )
}

// 获取 table数据
function getTableData(
  pageNum: number,
  pageSize: number,
  setDataSource: Dispatch<SetStateAction<IRequestVO[]>>,
  setTotal: Dispatch<SetStateAction<number>>,
  setLoading: Dispatch<SetStateAction<boolean>>
) {
  setLoading(true)
  userCenterLoginRecordApi({ pageNum, pageSize, defaultOrderFlag: true })
    .then(({ data }) => {
      setDataSource(data.data.records)
      setTotal(data.data.total)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}
